package com.tanhua.dubbo.api.db;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.domain.db.*;
import com.tanhua.domain.vo.AnswersVo;
import com.tanhua.domain.vo.SimilarYouVo;
import com.tanhua.dubbo.api.db.QuestionnaireReportApi;
import com.tanhua.dubbo.api.db.SoulTestApi;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.mapper.OptionMapper;
import com.tanhua.dubbo.mapper.QuestionUserMapper;
import com.tanhua.dubbo.mapper.QuestionnaireMapper;
import com.tanhua.dubbo.mapper.SoulQuestionMapper;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author
 * @create 2021/8/6 20:51
 */
@Service
public class SoulTestApiImpl implements SoulTestApi {
    @Autowired
    private QuestionUserMapper questionUserMapper;
    @Autowired
    private QuestionnaireMapper questionnaireMapper;
    @Autowired
    private SoulQuestionMapper soulQuestionMapper;
    @Autowired
    private OptionMapper optionMapper;
    @Autowired
    private QuestionnaireReportApi questionnaireReportApi;
    @Autowired
    private UserInfoApi userInfoApi;

    /**
     * 根据用户的id查找他对应的所有问卷
     * @param userId
     * @return
     */
    @Override
    public List<QuestionUser> findQuestionUserByUserId(Long userId) {
        QueryWrapper<QuestionUser> questionUserQueryWrapper = new QueryWrapper<>();
        return questionUserMapper.selectList(questionUserQueryWrapper.eq("user_id",userId));
    }

    @Override
    public List<Questionnaire> findAllQuestionnaire() {
        return questionnaireMapper.selectList(null);
    }

    @Override
    public void saveUserAndQuestionnaire(Long userId, Questionnaire questionnaire) {
        QuestionUser questionUser = new QuestionUser();
        questionUser.setUserId(userId);
        questionUser.setQuestionnaireId(questionnaire.getId());
        questionUser.setIsLock(questionnaire.getIsLock());
        questionUser.setLevel(questionnaire.getLevel());
        questionUserMapper.insert(questionUser);
    }

    @Override
    public Questionnaire findQuestionnaireById(Long questionnaireId){
        Questionnaire questionnaire = questionnaireMapper.selectById(questionnaireId);
        List<SoulQuestion> soulQuestions = soulQuestionMapper.questSoulQuestionsByQuestionId (questionnaireId);
        for (SoulQuestion soulQuestion : soulQuestions) {
            List<Option> options = soulQuestionMapper.questOptions (Long.valueOf(soulQuestion.getId()));
            soulQuestion.setOptions(options);
        }
        questionnaire.setSoulQuestions(soulQuestions);
        return questionnaire;
    }

    @Override
    public Integer totalScore(List<AnswersVo> answersVos) {
        Integer totalScore = 0;
        for (AnswersVo answersVo : answersVos) {
            String questionId = answersVo.getQuestionId();
            String optionId = answersVo.getOptionId();
            Integer score = soulQuestionMapper.totalScoreByQuestionIdAndOptionId(Long.parseLong(questionId), Long.parseLong(optionId));
            totalScore += score;
        }
        return totalScore;
    }

    @Override
    public List<SimilarYouVo> findSimilarYouVo(Long userId, String logoText) {
        List<Long> userIds = questionnaireReportApi.getUserIds(logoText);
        List<UserInfo> userInfos = userInfoApi.userInfos(userIds);
        List<SimilarYouVo> similarYouVos = null;
        if (userInfos != null) {
            similarYouVos =userInfos.stream().filter(item -> !item.getId().equals(userId)).map(item -> {
                SimilarYouVo similarYouVo = new SimilarYouVo();
                similarYouVo.setId(item.getId().intValue());
                similarYouVo.setAvatar(item.getAvatar());
                return similarYouVo;
            }).collect(Collectors.toList());
        }
        return similarYouVos;
    }

    @Override
    public void saveQuestionUserReportId(Long userId,Long questionnaireId,Long reportId) {
        QueryWrapper<QuestionUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId).eq("questionnaire_id",questionnaireId);
        QuestionUser questionUser = questionUserMapper.selectOne(wrapper);
        questionUser.setReportId(reportId);
        questionUserMapper.updateById(questionUser);
    }

    @Override
    public Integer getQuestionnaireIdByQuestionId(Long questionId) {
        return soulQuestionMapper.selectById(questionId).getQuestionnaireId();
    }

    @Override
    public void unLock(Long userId) {
        List<QuestionUser> questionUsers = questionUserMapper.selectList(new QueryWrapper<QuestionUser>().eq("user_id", userId));
        QuestionUser questionUserUpdate = null;
        int index = 0;
        for (int i = 0; i < questionUsers.size(); i++) {
            QuestionUser questionUserNext = questionUsers.get(i);
            index = i;
            if (i == 0) {
                index = 1;
            }
            if (questionUserNext.getIsLock() == 1 && questionUsers.get(index -1).getReportId() !=null) {
                questionUserUpdate = questionUserNext;
                questionUserUpdate.setIsLock(0);
                break;
            }
        }
        if (questionUserUpdate != null) {
            QueryWrapper<QuestionUser> questionUserQueryWrapper = new QueryWrapper<>();
            questionUserQueryWrapper.eq("questionnaire_id",questionUserUpdate.getQuestionnaireId());
            questionUserQueryWrapper.eq("user_id",userId);
            questionUserMapper.update(questionUserUpdate,questionUserQueryWrapper);
        }
    }
}
